package cn.krui.project.pubsub.system;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;

import cn.krui.helper.pub_sub.SubThread;

/**
 * @author zc
 * system 模块消息订阅者
 */
public class SubThreadSystem extends SubThread {
    private static final Logger logger = LoggerFactory.getLogger(SubThreadSystem.class);
    private JedisPool jedisPool;
    private Jedis jedis;
    private SubscriberSystem subscriberSystem;
    /**
     * 消息频道
     */
    private final String channel = "system_channel";
    /**
     * redis连接地址
     */
    private String springRedisHost;
    /**
     * redis端口
     */
    private int springRedisPort;
    /**
     * redis超时
     */
    private int springRedisTimeout;
    /**
     * redis连接密码
     */
    private String springRedisPassword;

    public SubThreadSystem(String springRedisHost, int springRedisPort, int springRedisTimeout,
            String springRedisPassword,StringRedisTemplate redisTemplate) {
        this.springRedisHost = springRedisHost;
        this.springRedisPort = springRedisPort;
        this.springRedisTimeout = springRedisTimeout;
        this.springRedisPassword = springRedisPassword;
        subscriberSystem = new SubscriberSystem(redisTemplate);
    }

    @Override
    public void run() {
        try {
            if (StringUtils.isEmpty(springRedisPassword)) {
                this.jedisPool = new JedisPool(new JedisPoolConfig(), springRedisHost, springRedisPort,
                        springRedisTimeout);
            } else {
                this.jedisPool = new JedisPool(new JedisPoolConfig(), springRedisHost, springRedisPort,
                        springRedisTimeout, springRedisPassword);
            }
            logger.info(String.format("system模块消息订阅者, 频道 %s, 线程将会被阻塞", channel));
            //取出一个连接
            jedis = jedisPool.getResource();
            //通过subscribe 的api去订阅，入参是订阅者和频道名
            jedis.subscribe(subscriberSystem, channel);
            jedisPool.close();
            jedis.close();
        } catch (Exception e) {
            logger.error(String.format("%s", e));
            if (jedisPool != null){
                jedisPool.close();
            }
            if (jedis != null){
                jedis.close();
            }
            super.interrupt();
        }
    }

    @Override
    public void destroy() {
        this.jedisPool.close();
        this.jedis.close();
        super.interrupt();
    }

}